package Sort;

import java.util.Arrays;
import java.util.ServiceLoader;

public class SelectSort {

    public void operation(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            swap(arr, i, minIndex);
        }
    }

    public void operation2(int[] arr) {
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int minIndex = left;
            int maxIndex = left;
            for (int i = left + 1; i <= right; i++) {
                if (arr[i] < arr[minIndex]) {
                    minIndex = i;
                }
                if (arr[i] > arr[maxIndex]) {
                    maxIndex = i;
                }
            }
            if (maxIndex != left) {
                swap(arr, left, minIndex);
            }
            swap(arr, right, maxIndex);
            left++;
            right--;
        }
    }

    public void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static void main(String[] args) {
        int[] arr = {-74,48,-20,2,10,-84,-5,-9,11,-24,-91,2,-71,64,63,80,
                28,-30,-58,-11,-44,-87,-22,54,-74,-10,-55,-28,-46,29,10,50,
                -72,34,26,25,8,51,13,30,35,-8,50,65,-6,16,-2,21,-78,35,-13,
                14,23,-3,26,-90,86,25,-56,91,-13,92,-25,37,57,-20,-69,98,95,
                45,47,29,86,-28,73,-44,-46,65,-84,-96,-24,-12,72,-68,93,57,92,
                52,-45,-2,85,-63,56,55,12,-85,77,-39};

        SelectSort selectSort = new SelectSort();
        selectSort.operation2(arr);
        System.out.println(Arrays.toString(arr));
    }

}
